package com.ddh.ddhsanguogame.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

public class JwtUtil {

    private static final String SECRET_KEY = "card-game"; // 替换为你的密钥

    /**
     * 生成 JWT Token（仅用用户 ID）
     *
     * @param userId 用户 ID
     * @param expireTime 过期时间（毫秒）
     * @return JWT Token
     */
    public static String generateToken(String userId, long expireTime) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + expireTime);

        return JWT.create()
                .withClaim("userId", userId)
                .withIssuedAt(now)
                .withExpiresAt(expiryDate)
                .sign(Algorithm.HMAC256(SECRET_KEY));
    }

    /**
     * 解析 JWT Token 并获取用户 ID
     *
     * @param token JWT Token
     * @return 用户 ID
     * @throws JWTVerificationException 如果 Token 无效
     */
    public static String getUserIdFromToken(String token) throws JWTVerificationException {
        DecodedJWT decodedJWT = decodeToken(token);
        return decodedJWT.getClaim("userId").asString();
    }

    /**
     * 解析 JWT Token
     *
     * @param token JWT Token
     * @return DecodedJWT 对象
     * @throws JWTVerificationException 如果 Token 无效
     */
    public static DecodedJWT decodeToken(String token) throws JWTVerificationException {
        return JWT.require(Algorithm.HMAC256(SECRET_KEY))
                .build()
                .verify(token);
    }
}

